package com.csaba.util;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.logging.Logger;

public class DefaultI18NProvider implements I18NProvider
{
	private final static Logger logger = LoggerHelper.getDefaultLogger();
	private static final String FILE_NAME = "messages";
	private final static Map<String, ResourceBundle> resources = new HashMap<String, ResourceBundle>();
	private final static ResourceBundle NULL_BUNDLE = new ResourceBundle()
	{

		@Override
		public Enumeration<String> getKeys()
		{
			return null;
		}

		@Override
		protected Object handleGetObject( final String key )
		{
			return null;
		}
	};

	private final Locale locale;

	public DefaultI18NProvider()
	{
		this(Locale.getDefault());
	}

	public DefaultI18NProvider( final Locale locale )
	{
		this.locale = locale;
	}

	public ResourceBundle getBundle( final Object namespace )
	{
		final String packageName = namespace.getClass().getPackage().getName();
		return getBundle(packageName);
	}

	private ResourceBundle getBundle( final String packageName )
	{
		if ( !resources.containsKey(packageName) )
		{
			try
			{
				final ResourceBundle bundle = ResourceBundle.getBundle(packageName + "." + FILE_NAME, locale);
				synchronized ( resources )
				{
					resources.put(packageName, bundle);
				}
			}
			catch ( final Exception e )
			{
				//unable to get resource for the package
				logger.warning("No localization available for package " + packageName);
				synchronized ( resources )
				{
					resources.put(packageName, NULL_BUNDLE);
				}
			}
		}
		final ResourceBundle bundle = resources.get(packageName);
		if ( bundle == NULL_BUNDLE )
			return null;

		return bundle;
	}

}
